package com.sean.example.databases;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class BaseDao<T> {

	public static final String TAG = "BaseDao";
	public static final int OPEN_READABLE = 0;
	public static final int OPEN_WRITABLE = 1;
	
	private DBHelper mDBHelper;
	protected SQLiteDatabase mDatabase;
	private String mTableName;
	private Class<T> mClass;
	
	public BaseDao(Context context, Class<T> cla) {
		mDBHelper = DBHelper.getInstance(context);
		mTableName = SQLUtil.getTableName(cla);
		mClass = cla;
	}
	
	public void open(int mode) {
		switch(mode) {
		case OPEN_READABLE:
			mDatabase = mDBHelper.getReadableDatabase();
			break;
		case OPEN_WRITABLE:
			mDatabase = mDBHelper.getWritableDatabase();
			break;
		}
	}
	
	/**
	 * 如果插入成功，则返回插入的ID，如果失败，则返回-1
	 */
	public long save(T obj) {
		SQLiteDatabase database = mDBHelper.getReadableDatabase();
		ContentValues cv = SQLUtil.beanToContentValues(obj);
		long id = database.insert(mTableName, null, cv);
		database.close();
		if(id != -1) {
			Log.d(TAG, "Insert a record to the table : " + mTableName + " >> id = " + id);
		} else {
			Log.w(TAG, "Can't insert a record to the table : " + mTableName + " >> id = " + id);
		}
		return id;
	}
	
	public boolean delete(T obj) {
		String id = SQLUtil.getIdByBean(obj);
		return delete(id);
	}
	
	public boolean delete(long id) {
		return delete(String.valueOf(id));
	}
	
	public boolean delete(String id) {
		SQLiteDatabase database = mDBHelper.getWritableDatabase();
		int count = database.delete(mTableName, "id=?", new String[]{id});
		database.close();
		if(count > 0) {
			Log.d(TAG, "Delete a record from the table : " + mTableName + " >> id = " + id);
			return true;
		} else {
			Log.w(TAG, "Fail to delete a record from the table : " + mTableName + " >> id = " + id);
			return false;
		}
	}
	
	public T get(long id) {
		return get(String.valueOf(id));
	}
	
	public T get(String id) {
		try {
			T obj = mClass.newInstance();
			SQLiteDatabase database = mDBHelper.getReadableDatabase();
			Cursor cursor = database.query(mTableName, null, "id=?", new String[]{id}, null, null, null);
			if(SQLUtil.cursorToBean(cursor, obj)) {
				Log.d(TAG, "Get a record from the table : " + mTableName);
				return obj;
			}
			database.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.w(TAG, "Fail to get a record from the table : " + mTableName);
		return null;
	}
	
}
